/**
 *
 *  @author   ghh
 *  @version  1.0
 */
define(['request', 'hciCore', 'hciMask', 'hciEmpty', 'hciPage'], function (Request, hciCore, HCIMask, HCIEmpty, HCIPage) {
    var HCIGrid = function (params) {
        var self = this;
        self.params = $.extend(true, {}, self.params, params || {});
        self.params.resultDataJSON = {};//用来存储数据
        self.params.row.checkbox = parseInt(self.params.row.checkbox);//将传进来的值转成数字
        self.params.row.treeCheckboxType = parseInt(self.params.row.treeCheckboxType);
        if (typeof (self.params.row.onCheck) == "function") {
            var _onCheck = self.params.row.onCheck;
            self.params.row.onCheck = function (isChecked, rowData) {
                _onCheck(isChecked, rowData);
                if (isChecked && self.getRowCountInPage() == self.getCheckRowCountInPage()) {
                    $("#" + self.ids.headId).find(".hci-grid-head-checkbox").addClass("hci-grid-checked");
                } else {
                    $("#" + self.ids.headId).find(".hci-grid-head-checkbox").removeClass("hci-grid-checked");
                }
            }
        }
        hciCore.container.call(self, self.params.target);//继承插件容器
        self._buildHtml();//创建外框


        self._buildHeadColumns();//创建表头列
        if (self.params.isUsePage) {
            self.hciPage = new HCIPage({
                target: self.ids.pageId,
                page: self.params.pageInfo["page"],
                totalSize: self.params.pageInfo["totalSize"],
                afterChangePage: function () {
                    self.loadData();
                }
            });
        }
        self._checkAllRows();
        self.resize();
        $(window).resize = function () {
            self.resize();
        };
        self.loadData();
    };
    HCIGrid.prototype.params = {
        target: '',
        primaryKey: 'id',
        width: '100%',
        height: '100%',
        isInitLoadData: true,
        isUsePage: true,
        dataAction: 'server',// 1、server；2、local
        pageInfo: {
            page: 1,
            totalSize: 0,
            afterChangePage: null
        },
        //合并列规则
        mergeColumnRule: function () {
            // return {byColumnName: [], mergeColumnName: []};
            return false;
        },
        ajax: {
            url: '',
            type: 'get'
        },
        columns: [],
        row: {
            checkbox: 2,//0 无选择框 | 1 单选 | 2 多选
            mergeCheckbox: false, // 当合并列时，是否合并选择框
            checkLinkageParent: false,//选择联动父节点
            unCheckLinkageParent: true,//取消选择联动父节点
            checkLinkageChildren: true,//选择联动子节点
            unCheckLinkageChildren: true,//取消选择联动子节点
            onlyCheckChildren: false,//只能选中子节点
            selectIndex: -1,
            isChecked: null,//
            checkField: '__checked',
            checkValue: true,
            onCheck: null,
            afterCheck: null, //选择后事件
            onSelect: null,//选择事件
            onClickRow: null,//点击tr时触发
            treeCheckboxType: 0,//0：正常选；1：disable;2:hidden
            checkTypeParentValue: '',
            isNumber: true //行号
        },
        showType: 'list',//1、list；2、tree；3、group；4、detail
        group: {
            name: '',
            display: '',
            onExtend: null,//分组展开事件
            onCollapse: null//分组收缩事件
        },
        tree: {
            simpleData: {
                enable: false,
                children: 'children',
                idKey: "id",
                pIdKey: 'pid',
                textField: 'name',
                _pIdKey: '__pid',
                rootPIdValue: '___hci_first_layer_001'
            },
            onExtend: null,//树展开事件
            onCollapse: null//树收缩事件
        },
        renderData: function (data) {
            return data.result;
        },
        data: {
            list: [],
            total: 0
        },
        diffHeight: 0,
        beforeLoadData: null,
        afterLoadData: null
    };
    HCIGrid.prototype.columnParams = {
        display: '',
        name: '',
        width: 120,
        align: 'left',
        type: 'string',//1、string；2、date；3、number
        render: null,
        format: "",
        fixed: 'def', // 1、def； 2、left； 3、right
        isEdit: false,//是否编辑
        editor: {
            stateType: 1,//1:只有编辑状态；2:两种状态①一种是编辑状态，②一种是表格展示状态
            type: 'text'//1、text;2、checkbox;3、date;4、select
        }
    };
    HCIGrid.prototype._setColumnsData = function () {
        var self = this, newColumns = [], id = 1;
        var columns2Array = function (data, pid) {
            for (var i in data) {
                data[i].id = id;
                data[i].pid = pid;
                if (data[i]["columns"]) {
                    newColumns.push({id: id, display: data[i].display, pid: data[i].pid});
                    id += 1;
                    columns2Array(data[i]["columns"], data[i].id);
                } else {
                    var columnInfo = $.extend(true, {}, self.columnParams, data[i]);
                    newColumns.push(columnInfo);
                    id += 1;
                }
            }
        };
        columns2Array(self.params.columns, 0);
        self.params.jsonColumns = hciCore.tree.array2json(newColumns, "id", "pid", "pid");
        self.params.allColumnCount = newColumns.length;
        newColumns = null;
        self.params.lastLayerColumns = [];
        var getLastLayerColumns = function (data) {
            $.each(data, function (index, item) {
                var isLast = true;
                $.each(data, function (index1, item1) {
                    if (item["id"] == item1["pid"]) {
                        isLast = false;
                        return false;
                    }
                });
                if (isLast) {
                    self.params.lastLayerColumns.push(item);
                }
            })
        }
        getLastLayerColumns(self.params.jsonColumns);
    };
    HCIGrid.prototype._setColumnsFixedStorage = function () {
        var self = this;
        self.params.fixedColumns = {
            "left": [],
            "def": [],
            "right": [],
            "leftWidth": 0,
            "defWidth": 0,
            "defOuterWidth": 0,
            "rightWidth": 0
        };
        var gridWidth = $("#" + self.ids.gridId).width();
        if (self.params.row.isNumber) {
            gridWidth = gridWidth - 36;
        }

        if (self.params.row.checkbox) {
            gridWidth = gridWidth - 32;
        }
        gridWidth = gridWidth - 22;//预留一点，用于存放滚动条
        $.each(self.params.lastLayerColumns, function (index, item) {
            if (typeof (item["width"]) == "string" && item["width"].indexOf("%") > -1) {
                item["_width"] = gridWidth * (parseFloat(item["width"]) / 100) - 10;
            } else {
                item["_width"] = item["width"] - 10;
            }
            self.params.fixedColumns[item["fixed"]].push(item);
            self.params.fixedColumns[item["fixed"] + "Width"] += item["_width"] + 11;
        });
        self.params.fixedColumns["defOuterWidth"] = gridWidth - self.params.fixedColumns["leftWidth"] - self.params.fixedColumns["rightWidth"];
    };
    HCIGrid.prototype._renderMultiColumns = function () {
        var self = this,
            columnJson = {
                count: {
                    left: self.params.fixedColumns["left"].length,
                    def: self.params.fixedColumns["def"].length,
                    right: self.params.fixedColumns["right"].length,
                    lastLayer: self.params.lastLayerColumns.length,
                    all: self.params.allColumnCount
                },
                height: {
                    left: 30,
                    def: 30,
                    right: 30,
                    max: 0
                },
                layer: {
                    left: 0,
                    def: 0,
                    right: 0,
                    max: 0
                }
            };
        if (columnJson.count.lastLayer < columnJson.count.all) {
            var columnFixedArray = self._getColumnFixedArray();
            for (var t in columnFixedArray) {
                var key = columnFixedArray[t];
                var i = true;
                while (i) {
                    var j = false;
                    var jqTr = $("<tr></tr>");
                    $(".hci-grid-head-columns-" + key + "-inner tr:first td", "#" + self.ids.headColumnsId).each(function () {
                        var _this = this;
                        var columnPId = $(_this).attr("data-column-pid");
                        if (columnPId && columnPId != "0") {
                            j = true;
                            var tdInfo = self.params.jsonColumns[columnPId];
                            var jqTd = $("<td></td>").attr({
                                "data-column-id": tdInfo["id"],
                                "data-column-pid": tdInfo["pid"]
                            });
                            var jqHeadColumnContent = $("<div class='hci-grid-head-columns-content'></div>").text(tdInfo["display"]);
                            jqTd.append(jqHeadColumnContent);
                            jqTr.append(jqTd)
                        }
                    });
                    if (!j) {
                        break;
                    } else {
                        columnJson.height[key] = columnJson.height[key] + 30;
                        columnJson.height["max"] = (columnJson.height["max"] > columnJson.height[key]) ? columnJson.height["max"] : columnJson.height[key];
                    }
                    $(".hci-grid-head-columns-" + key + "-inner tbody", "#" + self.ids.headColumnsId).prepend(jqTr);
                }
                columnJson.layer[key] = columnJson.height[key] / 30;
            }
            columnJson.layer["max"] = columnJson.height["max"] / 30;
            $("#" + self.ids.headColumnsId).css({"height": columnJson.height.max});
            /*填充缺失的Td*/
            for (var t in columnFixedArray) {
                var key = columnFixedArray[t];
                for (var i = 0; i < columnJson.count[key]; i++) {
                    for (var j = 0; j < columnJson.layer[key]; j++) {
                        var jqTd = $("#" + self.ids.headId).find(".hci-grid-head-columns-" + key + "-inner tr").eq(j).find("td")[i];
                        if (!jqTd) {
                            var _jqTd = $("<td></td>");
                            $("#" + self.ids.headId).find(".hci-grid-head-columns-" + key + "-inner tr").eq(j).append(_jqTd);
                        }
                    }
                }
            }
            /*循环调整表头呈现*/
            for (var t in columnFixedArray) {
                var key = columnFixedArray[t];
                for (var i = 0; i < columnJson.count[key]; i++) {
                    for (var j = 0; j < columnJson.layer[key]; j++) {
                        var jqTd = $("#" + self.ids.headId).find(".hci-grid-head-columns-" + key + "-inner tr").eq(j).find("td").eq(i);
                        var jqTdContent = jqTd.find(".hci-grid-head-columns-content");
                        if (jqTdContent.length == 0) {
                            for (var z = j; z < columnJson.layer[key]; z++) {
                                var _jqTd = $("#" + self.ids.headId).find(".hci-grid-head-columns-" + key + "-inner tr").eq(z).find("td").eq(i);
                                var columnId = _jqTd.attr("data-column-id");
                                var columnPId = _jqTd.attr("data-column-pid");
                                var lastColumnName = _jqTd.attr("data-last-column-name");
                                var _jqTdContent = _jqTd.find(".hci-grid-head-columns-content");
                                if (_jqTdContent.length > 0) {
                                    jqTd.append(_jqTdContent).attr({
                                        "data-column-id": columnId,
                                        "data-column-pid": columnPId,
                                        "data-last-column-name": lastColumnName
                                    });
                                    _jqTd.removeAttr("data-column-id");
                                    _jqTd.removeAttr("data-column-pid");
                                    _jqTd.removeAttr("data-last-column-name");
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            /*开始合并行*/
            for (var t in columnFixedArray) {
                var key = columnFixedArray[t];
                $("#" + self.ids.headId).find(".hci-grid-head-columns-" + key + "-inner tr").each(function () {
                    var jqTr = $(this);
                    var rowIndex = jqTr.index();
                    var preColumnId = "";
                    var preJQTd = null;
                    jqTr.find("td").each(function () {
                        var jqTd = $(this);
                        var columnId = jqTd.attr("data-column-id");
                        if (columnId && preColumnId == columnId) {
                            var colSpan = preJQTd.attr("colSpan") || 1;
                            preJQTd.attr({"colSpan": colSpan + 1});
                            jqTd.remove();
                        } else {
                            preColumnId = columnId;
                            preJQTd = jqTd;
                        }
                        if (jqTd.find(".hci-grid-head-columns-content").length == 0) {
                            jqTd.remove();
                        }
                        var lastColumnName = jqTd.attr("data-last-column-name");
                        if (lastColumnName) {
                            var rowSpan = columnJson.layer[key] - rowIndex;
                            if (rowSpan > 1) {
                                jqTd.attr({"rowSpan": rowSpan});
                            }
                            jqTd.find(".hci-grid-head-columns-content").css({
                                "height": (columnJson.layer["max"] - rowIndex) * 30,
                                "lineHeight": (columnJson.layer["max"] - rowIndex) * 30 + "px"
                            })
                        }
                    })
                });
            }
            $("#" + self.ids.headId).find(".hci-grid-head-columns-checkbox-outer").css({
                padding: (columnJson.height.max - 8) / 2 - columnJson.height.max / 30 - 1 + "px 8px"
            });
            columnJson = null;
        }
    };
    HCIGrid.prototype._buildHtml = function () {
        var self = this;
        var id = self.c[0].hciId;
        self.ids = {
            gridId: "hci-grid-" + id,
            headId: "hci-grid-head-" + id,
            headColumnsId: "hci-grid-head-columns-" + id,
            bodyId: "hci-grid-body-" + id,
            bodyRowsId: "hci-grid-body-rows-" + id,
            pageId: "hci-grid-page-" + id,
            emptyId: "hci-grid-empty-" + id
        };

        var gridHtml = '<div id="{gridId}" class="hci-grid-outer" style="width:{width};height:{height};">' +
            '<div id="{headId}" class="hci-grid-head">' +
            '<div id="{headColumnsId}" class="hci-grid-head-columns-outer" ></div>' +
            '</div>' +
            '<div id="{bodyId}" class="hci-grid-body">' +
            '<div id="{bodyRowsId}" class="hci-grid-body-rows-outer" ></div>' +
            '</div>' +
            '<div id="{pageId}"></div>' +
            '</div>';
        var width = typeof (self.params.width) == "number" ? self.params.width + "px" : self.params.width,
            height = typeof (self.params.height) == "number" ? self.params.height + "px" : self.params.height;
        var griHtmlPro = $.extend(true, {}, self.ids, {width: width, height: height});

        gridHtml = hciCore.template(gridHtml, griHtmlPro);
        self.c[0].container.append(gridHtml);
    };
    HCIGrid.prototype._buildHeadColumns = function () {
        var self = this;
        self._setColumnsData();
        self._setColumnsFixedStorage();
        var jqHeadColumns = $("#" + self.ids.headColumnsId);
        var left = 0;
        if (self.params.row.isNumber) {
            jqHeadColumns.append('<div class="hci-grid-head-column-row-number-outer"></div>');
            left += 36;
        }
        if (self.params.row.checkbox == 2) {
            jqHeadColumns.append('<div class="hci-grid-head-columns-checkbox-outer" style="left:' + left + 'px;"><div class="hci-grid-head-checkbox"></div></div>');
            left += 32;
        } else if (self.params.row.checkbox == 1) {
            jqHeadColumns.append('<div class="hci-grid-head-columns-checkbox-outer" style="left:' + left + 'px"></div>');
            left += 32;
        }
        var columnFixedArray = self._getColumnFixedArray();
        for (var t in columnFixedArray) {
            var key = columnFixedArray[t];
            var columnHtml = "";
            switch (key) {
                case "left":
                    columnHtml = '<div class="hci-grid-head-columns-' + key + '-outer" style="left:' + left + 'px;">';
                    break;
                case "def":
                    left = left + self.params.fixedColumns["leftWidth"];
                    var defOuterWidth = self.params.fixedColumns["defOuterWidth"];
                    var defWidth = self.params.fixedColumns["defWidth"];
                    var width = defOuterWidth < defWidth ? defOuterWidth : defWidth;
                    columnHtml = '<div class="hci-grid-head-columns-' + key + '-outer" style="left:' + left + 'px;width:' + width + 'px;">';
                    break;
                case "right":
                    var defOuterWidth = self.params.fixedColumns["defOuterWidth"];
                    var defWidth = self.params.fixedColumns["defWidth"];
                    var width = defOuterWidth < defWidth ? defOuterWidth : defWidth;
                    left = left + width;
                    columnHtml = '<div class="hci-grid-head-columns-' + key + '-outer" style="left:' + left + 'px;">';
                    break;
            }
            columnHtml += '<div class="hci-grid-head-columns-' + key + '-inner">' +
                '<table class="hci-grid-head-columns-table" cellspacing="0" cellpadding="0">' +
                '<tbody><tr></tr></tbody>' +
                '</table>' +
                '</div>' +
                '</div>';
            jqHeadColumns.append(columnHtml);
            $.each(self.params.fixedColumns[key], function (index, item) {
                var jqTd = $("<td></td>").attr({
                        "data-column-id": item["id"],
                        "data-column-pid": item["pid"],
                        "data-last-column-name": item["name"]
                    }),
                    jqHeadColumnContent = $("<div></div>").addClass("hci-grid-head-columns-content").css({
                        "width": item["_width"],
                        "text-align": "center"
                    }).text(item["display"]);
                jqTd.append(jqHeadColumnContent);
                jqHeadColumns.find(".hci-grid-head-columns-" + key + "-inner tr").append(jqTd);
            });
        }
        self._renderMultiColumns();
        self._colResize();
    };
    HCIGrid.prototype._colResize = function () {
        var self = this;
        $("#" + self.ids.headId).find("td[data-last-column-name]").each(function () {
            var jqHeadColumnContent = $(this).find(".hci-grid-head-columns-content");
            var po = jqHeadColumnContent.offset();
            var width = jqHeadColumnContent.innerWidth() - 2;
            var height = jqHeadColumnContent.outerHeight();
            var jqHeadColumnResize = $("<div></div>").addClass("hci-grid-head-column-resize").css({
                top: po.top,
                left: po.left + width,
                height: height
            });
            $(this).append(jqHeadColumnResize);
        });
        var moveFlag = false, target;
        $(document).on("mousemove", function (e) {
            var ex = e || window.event;
            var mouseX = ex.pageX;
            if (moveFlag && target !== null && target !== "") {
                var offsetLeft = target.offset().left;
                var marginLeft = mouseX - offsetLeft;
                var toX = mouseX - marginLeft;
                target.css({"left": toX});
                var jqTd = target.closest("td");
                var columnName = jqTd.attr("data-last-column-name");
                var jqHeadColumnContent = jqTd.find(".hci-grid-head-columns-content");
                var colLeft = jqHeadColumnContent.offset().left;
                var columnWidth = mouseX - colLeft;
                jqHeadColumnContent.innerWidth(columnWidth);
                var columnFixedArray = self._getColumnFixedArray();
                for (var t in columnFixedArray) {
                    var key = columnFixedArray[t];
                    $(self.params.fixedColumns[key]).each(function (index, item) {
                        var colName = item["name"];
                        if (columnName === colName) {
                            self.params.fixedColumns[key][index]["width"] = columnWidth;
                            var outer = $("#" + self.ids.bodyRowsId).find(".hci-grid-body-rows-" + key + "-inner");
                            outer.find("td[data-grid-name='" + columnName + "']").find(".hci-grid-body-td-content").innerWidth(columnWidth);
                        }
                    });
                }
                self.resize();
            }
        });
        var colResize = function (obj) {
            obj.on("mousedown", function (e) {
                target = obj;
                moveFlag = true;
            })
        };
        $(document).mouseup(function () {
            $("#" + self.ids.headColumnsId).find(".hci-grid-head-columns-content").each(function () {
                var _this = this;
                var coordinates = $(_this).offset();
                var spanWidth = $(_this).outerWidth();
                var left = coordinates.left + spanWidth;
                $(_this).closest("td").find(".hci-grid-head-column-resize").css({left: left - 2});
            });
            moveFlag = false;
            target = null;
        });
        $("#" + self.ids.headColumnsId).find(".hci-grid-head-column-resize").each(function () {
            colResize($(this));
        });
    };
    HCIGrid.prototype._getColumnFixedArray = function () {
        var self = this;
        var columnFixedArray = [];
        if (self.params.fixedColumns["left"].length > 0) {
            columnFixedArray.push("left");
        }
        if (self.params.fixedColumns["def"].length > 0) {
            columnFixedArray.push("def");
        }
        if (self.params.fixedColumns["right"].length > 0) {
            columnFixedArray.push("right");
        }
        return columnFixedArray;
    };
    HCIGrid.prototype._rowEvent = function () {
        var self = this;
        var jqBody = $("#" + self.ids.bodyId);
        var aTrArray = [".hci-grid-body-row-checkbox-outer", ".hci-grid-body-rows-def-inner tr", ".hci-grid-body-rows-left-inner tr", ".hci-grid-body-rows-right-inner tr"];
        var aTr = aTrArray.join(",");
        $(aTr, jqBody).hover(function () {
            var num = $(this).index();
            var mergeSing = $(this).attr("mergeSign");
            $.each(aTrArray, function (index, item) {
                $(item, jqBody).eq(num).addClass("hci-grid-body-rows-table-tr-hover");
            })
            $(jqBody).find("tr[mergeSign='" + mergeSing + "']").addClass("hci-grid-body-rows-table-tr-hover");
        }, function () {
            $(aTr, jqBody).removeClass("hci-grid-body-rows-table-tr-hover");
        }).on("click", function () {
            var primaryKeyValue = $(this).data("primaryKeyValue");
            var mergeSing = $(this).attr("mergeSign");
            var rowData = self.params.resultDataJSON[primaryKeyValue];
            $(aTr, jqBody).removeClass("hci-grid-body-rows-table-tr-selected");
            var num = $(this).index();
            $.each(aTrArray, function (index, item) {
                $(item, jqBody).eq(num).addClass("hci-grid-body-rows-table-tr-selected");
            });
            $(jqBody).find("tr[mergeSign='" + mergeSing + "']").addClass("hci-grid-body-rows-table-tr-selected");
            if (typeof (self.params.row.onSelect) == "function") {
                self.params.row.onSelect(rowData);
            }
            if (typeof (self.params.row.onClickRow) == "function") {
                self.params.row.onClickRow(rowData);
            }
        });
    };
    HCIGrid.prototype._loadLocalData = function () {
        var self = this;
        var jqBodyRows = $("#" + self.ids.bodyRowsId);
        if (self.params.isUsePage) {
            self.hciPage.setTotalSize(self.params.data.total);
        }
        var left = 0;
        if (self.params.row.isNumber) {
            var bodyRowsNumberOuter = "<div class='hci-grid-body-rows-number-outer'></div>";
            jqBodyRows.append(bodyRowsNumberOuter);
            left += 36;
        }
        switch (self.params.row.checkbox) {
            case 1:
            case 2:
                var bodyCheckboxHtml = "<div class='hci-grid-body-rows-checkbox-outer' style='left:" + left + "px'></div>";
                left += 32;
                jqBodyRows.append(bodyCheckboxHtml);
                break;
        }
        var columnFixedArray = self._getColumnFixedArray();
        for (var t in columnFixedArray) {
            var key = columnFixedArray[t];
            var rowsHtml = "";
            switch (key) {
                case "left":
                    rowsHtml = '<div class="hci-grid-body-rows-' + key + '-outer"  style="left:' + left + 'px">';
                    break;
                case "def":
                    left = left + self.params.fixedColumns["leftWidth"];
                    var defOuterWidth = self.params.fixedColumns["defOuterWidth"];
                    var defWidth = self.params.fixedColumns["defWidth"];
                    var width = defOuterWidth < defWidth ? defOuterWidth : defWidth;
                    var _left = left + $("#" + self.ids.gridId).offset().left;
                    rowsHtml = '<div class="hci-grid-body-rows-' + key + '-outer"  style="width: ' + width + 'px;left:' + _left + 'px;">';
                    break;
                case "right":
                    var defOuterWidth = self.params.fixedColumns["defOuterWidth"];
                    var defWidth = self.params.fixedColumns["defWidth"];
                    var width = defOuterWidth < defWidth ? defOuterWidth : defWidth;
                    left = left + width;
                    rowsHtml = '<div class="hci-grid-body-rows-' + key + '-outer"  style="left:' + left + 'px">';
                    break;
            }
            rowsHtml += '<div class="hci-grid-body-rows-' + key + '-inner">' +
                '<table class="hci-grid-body-rows-table" cellspacing="0" cellpadding="0">' +
                '<tbody>' +
                '</tbody>' +
                '</table>' +
                '</div>' +
                '</div>';
            jqBodyRows.append(rowsHtml);
        }
        //列合并处理
        var mergeColumnRule = self.params.mergeColumnRule();


        if (typeof (self.params.beforeLoadData) == "function") {
            self.params.beforeLoadData(self.params.data);
        }

        switch (self.params.showType) {
            case "list":
                var bySameColumnSign = 0;
                var byPreValue;
                var mergeColumnInfo = {};
                $.each(self.params.data.list, function (rowIndex, rowData) {
                    if (mergeColumnRule) {
                        var byColumnValue = '';
                        $.each(mergeColumnRule["byColumnName"], function (idx, byColumnName) {
                            if ((rowData[byColumnName] === '' && rowData[byColumnName] == '') || (rowData[byColumnName] === 0 && rowData[byColumnName] == null)) {
                                byColumnValue += hciCore.randomId() + "_";
                            } else {
                                byColumnValue += rowData[byColumnName] + "_";
                            }
                        });
                        if (byColumnValue == byPreValue) {
                            mergeColumnInfo[byColumnValue + "_" + bySameColumnSign].push(rowIndex);
                        } else {
                            bySameColumnSign = bySameColumnSign + 1;
                            mergeColumnInfo[byColumnValue + "_" + bySameColumnSign] = [rowIndex];
                            byPreValue = byColumnValue;
                        }
                    }
                    self.addRow(rowData);
                });
                if (mergeColumnRule) {
                    self.mergeColumnInfo = mergeColumnInfo;
                }
                self._diffScrollHeight();
                break;
            case "tree":
                var bySameColumnSign = 0;
                var byPreValue;
                var mergeColumnInfo = {};

                var idKey = self.params.tree.simpleData.idKey;
                var pIdKey = self.params.tree.simpleData.pIdKey;
                var _pIdKey = self.params.tree.simpleData._pIdKey;
                var textField = self.params.tree.simpleData.textField;
                var rootPIdValue = self.params.tree.simpleData.rootPIdValue;
                var treeData = hciCore.tree.setFirstLayerPId(self.params.data.list, idKey, pIdKey, _pIdKey, rootPIdValue);
                var loadTreeData = function (idValue, data, _pIdKey) {
                    var nextChildrenData = hciCore.tree.getNextLayerChildren(data, idValue, _pIdKey);
                    if (nextChildrenData.length > 0) {
                        for (var i in nextChildrenData) {
                            self.addRow(nextChildrenData[i]);
                            loadTreeData(nextChildrenData[i][idKey], data, _pIdKey);
                        }
                    }
                }
                loadTreeData(rootPIdValue, treeData, _pIdKey);

                // 树形式展示渲染
                $("#" + self.ids.bodyRowsId).find('td[data-tree-text="' + textField + '"]').each(function () {
                    var _this = this;
                    var treePId = $(_this).attr("data-tree-pid");
                    var treeId = $(_this).attr("data-tree-id");
                    var jqParent = $("#" + self.ids.bodyRowsId).find('td[data-tree-id="' + treePId + '"]');
                    if (jqParent.length > 0) {
                        var paddingLeft = jqParent.find(".hci-grid-body-td-content").css("padding-left") || 0;
                        paddingLeft = parseInt(paddingLeft);
                        var width = $(_this).find(".hci-grid-body-td-content").css("width");
                        width = parseInt(width);
                        $(_this).find(".hci-grid-body-td-content").css({
                            "padding-left": paddingLeft + 30,
                            "width": width - paddingLeft - 25
                        })
                        var layer = $(jqParent).closest("tr").attr("data-tree-layer");
                        layer = parseInt(layer);
                        $(_this).closest("tr").attr({"data-tree-layer": layer + 1});
                    } else {
                        $(_this).find(".hci-grid-body-td-content").css({"padding-left": 5});
                        var layer = 0;
                        $(_this).closest("tr").attr({"data-tree-layer": layer});
                    }
                    var jqChild = $("#" + self.ids.bodyRowsId).find('td[data-tree-pid="' + treeId + '"]');
                    if (jqChild.length > 0) {
                        $(_this).find(".hci-grid-body-td-content").find(".hci-grid-tree-icon").on("click", function () {
                            var isOpen = false;
                            if ($(this).hasClass("hci-grid-tree-open")) {
                                $(this).removeClass("hci-grid-tree-open").addClass("hci-grid-tree-close");
                            } else {
                                isOpen = true;
                                $(this).removeClass("hci-grid-tree-close").addClass("hci-grid-tree-open");
                            }
                            var jqTr = $(this).closest("tr");
                            var layer = jqTr.attr("data-tree-layer");
                            var jqTrs = jqTr.nextAll("tr");
                            jqTrs.each(function () {
                                var _layer = $(this).attr("data-tree-layer");
                                if (layer >= _layer) {
                                    return false;
                                }
                                var trIndex = $(this).index();
                                var jqBodyRows = $("#" + self.ids.bodyRowsId);
                                var jqNumber = jqBodyRows.find(".hci-grid-body-row-number").eq(trIndex);
                                var jqCheckboxOut = jqBodyRows.find(".hci-grid-body-row-checkbox-outer").eq(trIndex);
                                var jqLeftTr = jqBodyRows.find(".hci-grid-body-rows-left-inner tr").eq(trIndex);
                                var jqDefTr = jqBodyRows.find(".hci-grid-body-rows-def-inner tr").eq(trIndex);
                                var jqRightTr = jqBodyRows.find(".hci-grid-body-rows-right-inner tr").eq(trIndex);
                                if (isOpen) {
                                    jqNumber.show();
                                    jqCheckboxOut.show();
                                    jqLeftTr.show();
                                    jqDefTr.show();
                                    jqRightTr.show();
                                } else {
                                    jqNumber.hide();
                                    jqCheckboxOut.hide();
                                    jqLeftTr.hide();
                                    jqDefTr.hide();
                                    jqRightTr.hide();
                                }
                            });
                        }).addClass("hci-grid-tree-open");
                        if (self.params.row.onlyCheckChildren) {
                            self.params.row.checkLinkageParent = false;//选择联动父节点
                            self.params.row.unCheckLinkageParent = false;//取消选择联动父节点
                            var index = $(_this).find(".hci-grid-body-td-content").find(".hci-grid-tree-icon").closest("tr").index();
                            $("#" + self.ids.bodyRowsId).find(".hci-grid-body-checkbox").eq(index).css({"visibility": "hidden"});
                        }
                    }
                });
                /*渲染checkbox 的父子节点层级属性*/
                $("#" + self.ids.bodyRowsId).find("[data-tree-layer]").each(function (idx, itm) {
                    var jqCheckbox = $("#" + self.ids.bodyRowsId).find(".hci-grid-body-checkbox").eq(idx);
                    var jqCheckboxOuter = jqCheckbox.closest(".hci-grid-body-row-checkbox-outer");
                    jqCheckboxOuter.attr({"data-tree-layer": $(itm).attr("data-tree-layer")});

                });
                if (self.params.row.checkbox == 1) {
                    switch (self.params.row.treeCheckboxType) {
                        case 1:
                            break;
                        case 2:
                            var jqCheckboxOuter = $("#" + self.ids.bodyRowsId).find(".hci-grid-body-row-checkbox-outer[data-tree-id='" + self.params.row.checkTypeParentValue + "']");
                            jqCheckboxOuter.find(".hci-grid-body-checkbox").css({"visibility": "hidden"});
                            var layer = jqCheckboxOuter.attr("data-tree-layer");
                            var jqNextCheckboxOuters = jqCheckboxOuter.nextAll(".hci-grid-body-row-checkbox-outer", "#" + self.ids.bodyRowsId);
                            $.each(jqNextCheckboxOuters, function () {
                                var _layer = $(this).attr("data-tree-layer");
                                if (layer >= _layer) {
                                    return false;
                                }
                                $(this).find(".hci-grid-body-checkbox").css({"visibility": "hidden"});
                            });
                            break;
                    }
                }
                self._diffScrollHeight();
                break;
            case "group":
                var name = self.params.group.name;
                var display = self.params.group.display;
                var groupData = hciCore.array2group(self.params.data.list, name, display);
                $.each(groupData, function (index, item) {
                    self._addGroupRow(item["name"]);
                    $.each(item["list"], function (index1, item1) {
                        self.addRow(item1);
                    })
                });
                break;
        }
        self._rowEvent()
        if (typeof (self.params.afterLoadData) == "function") {
            self.params.afterLoadData(self.params.data);
        }
        if (self.params.row.selectIndex > -1) {
            var jqBody = $("#" + self.ids.bodyId);
            var aTrArray = [
                ".hci-grid-body-row-checkbox-outer",
                ".hci-grid-body-rows-def-inner tr",
                ".hci-grid-body-rows-left-inner tr",
                ".hci-grid-body-rows-right-inner tr"
            ];
            $.each(aTrArray, function (index, item) {
                $(item, jqBody).eq(self.params.row.selectIndex).addClass("hci-grid-body-rows-table-tr-selected");
            });
            if (typeof (self.params.row.onSelect) == "function") {
                var rowData = self.getSelectedRow();
                self.params.row.onSelect(rowData);
            }
        }
        if (mergeColumnRule) {
            var mergeLeftColumnIndexArray = [], mergeDefColumnIndexArray = [], mergeRightColumnIndexArray = [];
            $.each(mergeColumnRule["mergeColumnName"], function (index1, item1) {
                $.each(self.params.fixedColumns["left"], function (index, item) {
                    if (item1 == item["name"]) {
                        mergeLeftColumnIndexArray.push(index);
                    }
                });
                $.each(self.params.fixedColumns["def"], function (index, item) {
                    if (item1 == item["name"]) {
                        mergeDefColumnIndexArray.push(index);
                    }
                });
                $.each(self.params.fixedColumns["right"], function (index, item) {
                    if (item1 == item["name"]) {
                        mergeRightColumnIndexArray.push(index);
                    }
                });
            });
            if (mergeLeftColumnIndexArray.length > 0) {
                //对数字索引进行排序，保证列顺序
                mergeLeftColumnIndexArray.sort(function (x, y) {
                    return x - y;
                });
            }
            if (mergeDefColumnIndexArray.length > 0) {
                //对数字索引进行排序，保证列顺序
                mergeDefColumnIndexArray.sort(function (x, y) {
                    return x - y;
                });
            }
            if (mergeRightColumnIndexArray.length > 0) {
                //对数字索引进行排序，保证列顺序
                mergeRightColumnIndexArray.sort(function (x, y) {
                    return x - y;
                });
            }
            var jqCheckTrs = $("#" + self.ids.bodyId).find(".hci-grid-body-rows-checkbox-outer").find(".hci-grid-body-row-checkbox-outer");
            var jqLeftTrs = $("#" + self.ids.bodyId).find(".hci-grid-body-rows-left-outer").find(".hci-grid-body-rows-table").find("tr");
            var jqDefTrs = $("#" + self.ids.bodyId).find(".hci-grid-body-rows-def-outer").find(".hci-grid-body-rows-table").find("tr");
            var jqRightTrs = $("#" + self.ids.bodyId).find(".hci-grid-body-rows-right-outer").find(".hci-grid-body-rows-table").find("tr");
            $.each(mergeColumnInfo, function (_idx, rowIndexArray) {
                if (rowIndexArray.length > 1) {
                    //需要合并
                    var height = 31 * rowIndexArray.length + rowIndexArray.length - 1 + "px";
                    var checkboxHeight = 32 * (rowIndexArray.length - 1) + 15 + "px";
                    var lineHeight = height;
                    for (var i = 0; i < rowIndexArray.length; i++) {
                        var colLeftIndex = 0, colDefIndex = 0, colRightIndex = 0;
                        // 合并选择框
                        if (self.params.row.mergeCheckbox && jqCheckTrs) {
                            if (i == 0) {
                                jqCheckTrs.eq(rowIndexArray[i]).attr({"mergeSign": _idx}).css({
                                    "height": checkboxHeight,
                                    "display": "flex",
                                    "align-items": "center"
                                })
                            } else {
                                jqCheckTrs.eq(rowIndexArray[i]).attr({"mergeSign": _idx}).hide();
                            }
                        }
                        for (var j = 0; j < mergeLeftColumnIndexArray.length; j++) {
                            if (i == 0) {
                                jqLeftTrs.eq(rowIndexArray[i]).attr({"mergeSign": _idx}).find("td").eq(mergeLeftColumnIndexArray[j]).attr({"rowspan": rowIndexArray.length}).find(".hci-grid-body-td-content").css({
                                    "height": height,
                                    "line-height": lineHeight
                                });
                            } else {
                                jqLeftTrs.eq(rowIndexArray[i]).attr({"mergeSign": _idx}).find("td").eq(mergeLeftColumnIndexArray[j] - colLeftIndex).remove();
                                colLeftIndex = colLeftIndex + 1;
                            }
                        }
                        for (var j = 0; j < mergeDefColumnIndexArray.length; j++) {
                            if (i == 0) {
                                var jqTd = jqDefTrs.eq(rowIndexArray[i]).attr({"mergeSign": _idx}).find("td").eq(mergeDefColumnIndexArray[j]).attr({"rowspan": rowIndexArray.length}).find(".hci-grid-body-td-content").css({
                                    "height": height,
                                    "line-height": lineHeight
                                });

                            } else {
                                jqDefTrs.eq(rowIndexArray[i]).attr({"mergeSign": _idx}).find("td").eq(mergeDefColumnIndexArray[j] - colDefIndex).remove();
                                colDefIndex = colDefIndex + 1;
                            }
                        }
                        for (var j = 0; j < mergeRightColumnIndexArray.length; j++) {
                            if (i == 0) {
                                var jqTd = jqRightTrs.eq(rowIndexArray[i]).attr({"mergeSign": _idx}).find("td").eq(mergeRightColumnIndexArray[j])
                                    .attr({"rowspan": rowIndexArray.length})
                                    .find(".hci-grid-body-td-content").css({
                                        "height": height,
                                        "line-height": lineHeight
                                    });
                            } else {
                                jqRightTrs.eq(rowIndexArray[i]).attr({"mergeSign": _idx}).find("td").eq(mergeRightColumnIndexArray[j] - colRightIndex).remove();
                                colRightIndex = colRightIndex + 1;
                            }
                        }
                    }
                }
            })
        }
        self._bodyScroll();
        self.resize();
        //判断搜索列表是否为空
        if (self.params.data && self.params.data["list"]) {
            if (self.params.data && self.params.data["list"].length > 0) {
                var jqNoData = $("#" + self.ids.bodyRowsId).find(".hci-grid-no-data");
                jqNoData.hide();
            } else {
                var jqNoData = $("#" + self.ids.bodyRowsId).find(".hci-grid-no-data");
                if (jqNoData.length > 0) {
                    jqNoData.show();
                } else {
                    $("#" + self.ids.bodyRowsId).append("<div class='hci-grid-no-data'></div><div class='hci-grid-no-date-msg'>当前暂无数据 </div>")
                }
            }
        }
    };
    HCIGrid.prototype._diffScrollHeight = function () {
        var self = this;
        var obj = $(".hci-grid-body-rows-def-outer")[0];
        if (obj.scrollWidth > obj.clientWidth || obj.offsetWidth > obj.clientWidth) {
            $("#" + self.ids.bodyRowsId).find(".hci-grid-body-rows-number-outer").append("<div style='height: 18px;'></div>");
        }
    };
    HCIGrid.prototype._loadServerData = function (mask) {
        var self = this;
        var searchParam = {};
        if (self.params.isUsePage) {
            var pageNum = self.hciPage.params.page;
            var pageSize = self.hciPage.params.pageSize;
            searchParam = {pageNum: pageNum, pageSize: pageSize};
        }
        var data = {};
        if (typeof (self.params.ajax.data) == "function") {
            data = self.params.ajax.data();
        } else {
            data = self.params.ajax.data || {};
        }
        data = $.extend(true, {}, data, searchParam);
        var req = new Request(self.params.ajax.url);
        req[self.params.ajax.type]({
            data: data,
            success: function (data) {
                self.params.data = self.params.renderData(data);
                self._loadLocalData();
            },
            complete: function () {
                mask.hide();
            },
            error: function () {
                mask.hide();
            }
        })
    };
    HCIGrid.prototype._bodyScroll = function () {
        var self = this;
        $("#" + self.ids.bodyId).find(".hci-grid-body-rows-outer").scroll(function () {
            $("#" + self.ids.bodyId).find(".hci-grid-body-rows-def-inner").css({top: -this.scrollTop});
        });
        $("#" + self.ids.bodyId).find(".hci-grid-body-rows-def-outer").scroll(function () {
            $("#" + self.ids.headId).find(".hci-grid-head-columns-def-inner").css({left: -this.scrollLeft});
        })
    };
    HCIGrid.prototype._addTd = function (rowData, colInfo, jqTr) {
        var self = this;
        var tdInfo = $.extend(true, {}, self.columnParams, colInfo);
        tdInfo["_width"] = tdInfo["_width"];
        var value = "";
        switch (tdInfo["type"]) {
            case "date":
                tdInfo["format"] = tdInfo["format"] || "%Y-%m-%d";
                value = window.dhx4.template.date(rowData[tdInfo["name"]], tdInfo["format"]);
                break;
            case "number":
                value = hciCore.toNumber(rowData[tdInfo["name"]], tdInfo["format"]);
                break;
            default:
                value = rowData[tdInfo["name"]];
                break;
        }
        var jqTd = $("<td></td>");
        jqTd.attr("data-grid-name", tdInfo["name"]);
        var jqContent = $("<div></div>").addClass("hci-grid-body-td-content").css({
            width: tdInfo["_width"],
            "text-align": tdInfo["align"]
        });
        if (self.params.showType == "tree") {
            var textField = self.params.tree.simpleData.textField;
            var idKey = self.params.tree.simpleData.idKey;
            var _pIdKey = self.params.tree.simpleData._pIdKey;
            if (colInfo["name"] == textField) {
                jqTd.attr({
                    "data-tree-text": textField,
                    "data-tree-id": rowData[idKey],
                    "data-tree-pid": rowData[_pIdKey],
                });
                var jqSpanIcon = $("<span></span>").addClass("hci-grid-tree-icon");
                jqContent.append(jqSpanIcon);
            }
            var jqSpanText = $("<span></span>");
            if (typeof (tdInfo["render"]) == "function") {
                var jqRender = tdInfo["render"](rowData, value, colInfo, jqContent, jqTr);
                jqSpanText.append(jqRender);
            } else {
                value = value ? value : "";
                jqSpanText.text(value).attr({title: value});
            }
            jqContent.append(jqSpanText);
        } else {
            if (typeof (tdInfo["render"]) == "function") {
                var jqRender = tdInfo["render"](rowData, value, colInfo, jqContent, jqTr);
                jqContent.append(jqRender);
            } else {
                if (!colInfo.isEdit || tdInfo["editor"]["stateType"] != 1) {
                    value = value ? value : "";
                    var jqDiv = $("<div></div>").text(value);
                    jqContent.append(jqDiv).attr({title: value});
                }
            }
        }
        if (colInfo.isEdit) {
            switch (tdInfo["editor"]["type"]) {
                case "text":
                    var jqEditOuter = $("<div></div>").css({width: "100%", height: "30px"});
                    var jqInput = $("<input/>").attr({type: 'text'}).css({
                        width: "98%",
                        height: 20
                    }).val(value).on("keyup", function () {
                        var primaryKeyValue = $(this).closest("tr").data("primaryKeyValue");
                        self.params.resultDataJSON[primaryKeyValue][colInfo["name"]] = $(this).val();
                    });
                    jqEditOuter.append(jqInput);
                    jqContent.append(jqEditOuter);

                    break;
                case "select":
                    var jqEditOuter = $("<div></div>").css({width: "100%", height: "30px", "padding-top": "5px"});
                    var jqSelect = $("<select style=\"width:98%;\">" +
                        "<option value=\"the_adventures_of_tom_sawyer\">The Adventures of Tom Sawyer</option>" +
                        "<option value=\"the_dead_zone\">The Dead Zone</option>" +
                        "<option value=\"the_first_men_in_the_moon\">The First Men in the Moon</option>" +
                        "<option value=\"the_girl_who_loved_tom_gordon\">The Girl Who Loved Tom Gordon</option>" +
                        "<option value=\"the_green_mile\">The Green Mile</option>" +
                        "<option value=\"the_invisible_man\" selected=\"1\">The Invisible Man</option>" +
                        "<option value=\"the_island_of_doctor_moreau\">The Island of Doctor Moreau</option>" +
                        "<option value=\"the_prince_and_the_pauper\">The Prince and the Pauper</option>" +
                        "<option value=\"the_running_man\">The Running Man</option>" +
                        "<option value=\"the_talisman\">The Talisman</option>" +
                        "<option value=\"the_time_machine\">The Time Machine</option>" +
                        "<option value=\"the_tommyknockers\">The Tommyknockers</option>" +
                        "<option value=\"the_war_of_the_worlds\">The War of the Worlds</option>" +
                        "</select>");
                    jqEditOuter.append(jqSelect);
                    jqContent.append(jqEditOuter);
                    setTimeout(function () {
                        var jqComboSelect = dhtmlXComboFromSelect(jqSelect[0]);
                    }, 200);
                    break;
                case "date":
                    var jqEditOuter = $("<div></div>").css({width: "100%", height: "30px"});
                    var jqInput = $("<input type='text' class='hci-grid-date'/>").css({width: "98%", height: 20});
                    jqEditOuter.append(jqInput);
                    jqContent.append(jqEditOuter);
                    setTimeout(function () {
                        var jqCalendar = new dhtmlXCalendarObject(jqInput[0]);
                    }, 200);
                    break;
            }
        }
        jqTd.append(jqContent);
        return jqTd;
    };
    HCIGrid.prototype._checkAllRows = function () {
        var self = this;
        var jqHeadCheckbox = $(".hci-grid-head-checkbox", "#" + self.ids.headId);
        jqHeadCheckbox.on("click", function () {
            if ($(this).hasClass("hci-grid-checked")) {
                self.unCheckAll();
            } else {
                self.checkAll();
            }
        });
    };
    HCIGrid.prototype._addGroupRow = function (display) {
        var self = this;
        if (self.params.row.checkbox) {
            var jqRowCheckboxOuter = $('<div class="hci-grid-body-row-checkbox-outer"></div>');
            var jqRowCheckbox = $('<div class="hci-grid-body-checkbox"></div>');
            jqRowCheckboxOuter.append(jqRowCheckbox);
            $("#" + self.ids.bodyId).find(".hci-grid-body-rows-checkbox-outer").append(jqRowCheckboxOuter);
        }
        var columnFixedArray = self._getColumnFixedArray();
        for (var t in columnFixedArray) {
            var key = columnFixedArray[t];
            var jqTr = $("<tr></tr>");
            var jqContent = $("<div></div>").addClass("hci-grid-body-td-content");
            if (t == 0) {
                var jqSpanIcon = $("<span></span>").addClass("hci-grid-tree-icon hci-grid-tree-open").on("click", function () {

                });
                jqContent.append(jqSpanIcon);
                var jqSpanText = $("<span></span>").text(display);
                jqContent.append(jqSpanText);
            }
            var jqTd = $("<td></td>").attr({"colSpan": self.params.fixedColumns[key].length});
            jqTd.append(jqContent);
            jqTr.append(jqTd);
            $("#" + self.ids.bodyId).find(".hci-grid-body-rows-" + key + "-inner ").find("tbody").append(jqTr);
        }
    };
    HCIGrid.prototype.resize = function () {
        var self = this;
        var girdHeight = $("#" + self.ids.gridId).height();
        var gridColumnHeight = $("#" + self.ids.gridId).find(".hci-grid-head").height() + 5;
        var bodyHeight = girdHeight - gridColumnHeight;
        if (self.params.isUsePage) {
            bodyHeight = bodyHeight - 30;
        }
        var bodyWidth = $("#" + self.ids.bodyId).width();
        $("#" + self.ids.bodyRowsId).height(bodyHeight);
        $("#" + self.ids.bodyRowsId).width(bodyWidth);
        $("#" + self.ids.bodyRowsId).find(".hci-grid-body-rows-def-outer").height(bodyHeight);
        if (hciCore.hasScrollBar($("#" + self.ids.bodyRowsId).find(".hci-grid-body-rows-def-outer")[0], "h") && $("#" + self.ids.bodyRowsId).find(".grid-scroll-space").length == 0) {
            var spaceSize = hciCore.getScrollBarWidth() + 1;
            var spaceHtml = hciCore.template('<div style="height:{spaceSize}px;width:100%;" class="grid-scroll-space"></div>', {spaceSize: spaceSize});
            $("#" + self.ids.bodyRowsId).find(".hci-grid-body-rows-left-inner").append(spaceHtml);
            $("#" + self.ids.bodyRowsId).find(".hci-grid-body-rows-right-inner").append(spaceHtml);
        }
        self._setColumnsFixedStorage();
        var left = 0;
        if (self.params.row.isNumber) {
            left += 36;
        }
        switch (self.params.row.checkbox) {
            case 1:
            case 2:
                left += 32;
                break;
        }
        if (self.params.fixedColumns["left"].length > 0) {
            $("#" + self.ids.headColumnsId).find(".hci-grid-head-columns-left-outer").css({"left": left});
            $("#" + self.ids.bodyRowsId).find(".hci-grid-body-rows-left-outer").css({"left": left});
        }
        if (self.params.fixedColumns["def"].length > 0) {
            left = left + self.params.fixedColumns["leftWidth"];
            var defOuterWidth = self.params.fixedColumns["defOuterWidth"];
            var defWidth = self.params.fixedColumns["defWidth"];
            var width = 0;
            if (defOuterWidth < defWidth) {
                width = defOuterWidth;
            } else {
                width = defWidth;
            }
            var _left = left + $("#" + self.ids.gridId).offset().left;
            $("#" + self.ids.headColumnsId).find(".hci-grid-head-columns-def-outer").css({"left": left, width: width});
            $("#" + self.ids.bodyRowsId).find(".hci-grid-body-rows-def-outer").css({
                "left": _left,
                width: width
            });
        }
        if (self.params.fixedColumns["right"].length > 0) {
            $("#" + self.ids.headColumnsId).find(".hci-grid-head-columns-def-inner .hci-grid-head-columns-table td:last-child").css({"border-right": "0px"});
            $("#" + self.ids.bodyRowsId).find(".hci-grid-body-rows-def-inner .hci-grid-body-rows-table td:last-child").css({"border-right": "0px"});

            var defOuterWidth = self.params.fixedColumns["defOuterWidth"];
            var defWidth = self.params.fixedColumns["defWidth"];
            var width = defOuterWidth < defWidth ? defOuterWidth : defWidth;
            left = left + width;
            $("#" + self.ids.headColumnsId).find(".hci-grid-head-columns-right-outer").css({
                "left": left,
                "width": width
            });
            $("#" + self.ids.bodyRowsId).find(".hci-grid-body-rows-right-outer").css({"left": left});
        }
    };
    HCIGrid.prototype.addRow = function (rowData) {
        var self = this;
        var primaryKeyValue = rowData[self.params.primaryKey];//主键值
        self.params.resultDataJSON[primaryKeyValue] = rowData;
        if (self.params.row.isNumber) {
            var rowNum = $("#" + self.ids.bodyId).find(".hci-grid-body-row-number").length + 1;
            var jqRowNum = $("<div class='hci-grid-body-row-number'>" + rowNum + "</div>");
            $("#" + self.ids.bodyId).find(".hci-grid-body-rows-number-outer").append(jqRowNum);
            if (self.params.showType == "tree") {
                var textField = self.params.tree.simpleData.textField;
                var idKey = self.params.tree.simpleData.idKey;
                var _pIdKey = self.params.tree.simpleData._pIdKey;
                jqRowNum.attr({
                    "data-tree-text": textField,
                    "data-tree-id": rowData[idKey],
                    "data-tree-pid": rowData[_pIdKey]
                })
            }
        }
        if (self.params.row.checkbox) {
            var jqRowCheckboxOuter = $('<div class="hci-grid-body-row-checkbox-outer"></div>').data("primaryKeyValue", primaryKeyValue);
            if (self.params.showType == "tree") {
                var textField = self.params.tree.simpleData.textField;
                var idKey = self.params.tree.simpleData.idKey;
                var _pIdKey = self.params.tree.simpleData._pIdKey;
                jqRowCheckboxOuter.attr({
                    "data-tree-text": textField,
                    "data-tree-id": rowData[idKey],
                    "data-tree-pid": rowData[_pIdKey]
                })
            }
            var jqRowCheckbox = $('<div class="hci-grid-body-checkbox"></div>').on("click", function () {
                var jqCheckbox = $(this);
                self._checkbox(jqCheckbox, rowData);
            });
            jqRowCheckboxOuter.append(jqRowCheckbox);
            $("#" + self.ids.bodyId).find(".hci-grid-body-rows-checkbox-outer").append(jqRowCheckboxOuter);
        }
        var columnFixedArray = self._getColumnFixedArray();
        for (var t in columnFixedArray) {
            var key = columnFixedArray[t];
            var jqTr = $("<tr></tr>").data("primaryKeyValue", primaryKeyValue);
            $.each(self.params.fixedColumns[key], function (colIndex, colInfo) {
                var jqTd = self._addTd(rowData, colInfo, jqTr);
                jqTr.append(jqTd);
            });
            $("#" + self.ids.bodyId).find(".hci-grid-body-rows-" + key + "-inner ").find("tbody").append(jqTr);
        }


    };
    HCIGrid.prototype.loadData = function (data) {
        var self = this;
        self.params.resultDataJSON = {};
        $("#" + self.ids.bodyRowsId).empty();//加载新数据前清空旧数据
        $("#" + self.ids.headId).find(".hci-grid-head-checkbox").removeClass("hci-grid-checked");
        if (self.params.isInitLoadData) {
            if (self.params.dataAction == "server") {
                var mask = new HCIMask($("body"), {imgPath: GLOBAL_RESOURCE_PATH + "/script/core/ext/images/"});
                mask.show();
                self._loadServerData(mask);
            } else {
                self.params.data = data ? data : self.params.data;
                self._loadLocalData();
            }
        }
        self.params.isInitLoadData = true;
    };
    // 跳回首页加载数据
    HCIGrid.prototype.initLoadData = function (data) {
        var self = this;
        if (self.params.isUsePage && self.hciPage) {
            self.hciPage.setCurPage(1);
        }
        self.loadData(data);
    };
    HCIGrid.prototype.sortRows = function (colName, order) {
        //前端排序
        var self = this;
        self.params.data.list = self.params.data.list.sort(hciCore.arraySortFun(order, colName));
    };
    HCIGrid.prototype.checkAll = function () {
        var self = this;
        $("#" + self.ids.bodyId).find(".hci-grid-body-checkbox").each(function () {
            if (typeof (self.params.row.onCheck) == "function") {
                var primaryKeyValue = $(this).closest(".hci-grid-body-row-checkbox-outer").data("primaryKeyValue");
                var rowData = self.params.resultDataJSON[primaryKeyValue];
                self.params.row.onCheck(true, rowData);
            }
            $(this).addClass("hci-grid-checked");
        });
        $("#" + self.ids.headId).find(".hci-grid-head-checkbox").addClass("hci-grid-checked");
        if (typeof (self.params.row.afterCheck) == "function") {
            self.params.row.afterCheck(true)
        }
    };
    HCIGrid.prototype.unCheckAll = function () {
        var self = this;
        $("#" + self.ids.bodyId).find(".hci-grid-body-checkbox").each(function () {
            if (typeof (self.params.row.onCheck) == "function") {
                var primaryKeyValue = $(this).closest(".hci-grid-body-row-checkbox-outer").data("primaryKeyValue");
                var rowData = self.params.resultDataJSON[primaryKeyValue];
                self.params.row.onCheck(false, rowData);
            }
            $(this).removeClass("hci-grid-checked");
        })
        $("#" + self.ids.headId).find(".hci-grid-head-checkbox").removeClass("hci-grid-checked");
        if (typeof (self.params.row.afterCheck) == "function") {
            self.params.row.afterCheck(false)
        }
    };
    HCIGrid.prototype.getCheckedRows = function (fields) {
        var self = this;
        var rowsData = [];
        $("#" + self.ids.bodyRowsId).find(".hci-grid-body-row-checkbox-outer").each(function () {
            var _this = this;
            if ($(_this).find(".hci-grid-body-checkbox").hasClass("hci-grid-checked")) {
                var primaryKeyValue = $(this).data("primaryKeyValue");
                var _rowData = self.params.resultDataJSON[primaryKeyValue];
                var rowData = {};
                if (fields) {
                    $.each(fields, function (index, item) {
                        rowData[item] = _rowData[item];
                    })
                    _rowData = null;
                } else {
                    rowData = $.extend(true, {}, rowData, _rowData);
                    _rowData = null;
                }
                rowsData.push(rowData);
            }
        })
        return rowsData;
    };
    HCIGrid.prototype.setCheckedRows = function (primaryKeyValues) {
        var self = this;
        $("#" + self.ids.bodyRowsId).find(".hci-grid-body-row-checkbox-outer").each(function () {
            var primaryKeyValue = $(this).data("primaryKeyValue");
            var rowData = self.params.resultDataJSON[primaryKeyValue];
            var index = $.inArray(primaryKeyValue, primaryKeyValues);
            if (index > -1) {
                $(this).find(".hci-grid-body-checkbox").addClass("hci-grid-checked");
                if (typeof (self.params.row.onCheck) == "function") {
                    self.params.row.onCheck(true, rowData);
                }
            }
        });
    };
    HCIGrid.prototype.unCheckedRows = function (primaryKeyValues) {
        var self = this;
        $("#" + self.ids.bodyRowsId).find(".hci-grid-body-row-checkbox-outer").each(function () {
            var primaryKeyValue = $(this).data("primaryKeyValue");
            var rowData = self.params.resultDataJSON[primaryKeyValue];
            var index = $.inArray(primaryKeyValue, primaryKeyValues);
            if (index > -1) {
                $(this).find(".hci-grid-body-checkbox").removeClass("hci-grid-checked");
                self.params.row.onCheck(false, rowData);
            }
        });
    };
    HCIGrid.prototype.getSelectedRow = function () {
        var self = this;
        var primaryKeyValue = $("#" + self.ids.bodyRowsId).find(".hci-grid-body-rows-table-tr-selected:first").data("primaryKeyValue");
        var rowData = self.params.resultDataJSON[primaryKeyValue];
        return rowData;
    };
    HCIGrid.prototype.getCheckedPrimaryKeyValues = function (strJoin) {
        var self = this;
        var values = [];
        $("#" + self.ids.bodyRowsId).find(".hci-grid-body-row-checkbox-outer").each(function () {
            var _this = this;
            if ($(_this).find(".hci-grid-checked").length > 0) {
                values.push($(_this).data("primaryKeyValue"));
            }
        });
        if (strJoin) {
            values = values.join(",");
        }
        return values;
    };
    //获取当前页共有多少行数据
    HCIGrid.prototype.getRowCountInPage = function () {
        var self = this;
        var rows = $("#" + self.ids.bodyRowsId).find("table:first").find("tr");
        return rows.length;
    };
    HCIGrid.prototype.getCheckRowCountInPage = function () {
        var self = this;
        return self.getCheckedRows().length;
    };
    //获取表格当前数据
    HCIGrid.prototype.getData = function () {
        var self = this;
        var data = [];
        $.each(self.params.resultDataJSON, function (index, item) {
            data.push(item);
        });
        return data;
    };
    //更新行
    HCIGrid.prototype.updateRow = function (rowData) {
        var self = this;
        var primaryKeyValue = rowData[self.params.primaryKey];//主键值
        self.params.resultDataJSON[primaryKeyValue] = rowData;
    };
    HCIGrid.prototype._checkbox = function (jqCheckbox) {
        var self = this;
        var isCheck = !(jqCheckbox.hasClass("hci-grid-checked"));
        var jqCheckboxArray = [];//存储关联的对象
        if (self.params.row.checkbox == 1) {
            jqCheckboxArray.push(jqCheckbox);
        } else {
            var setParentArray = function () {
                var jqCheckOuter = jqCheckbox.closest(".hci-grid-body-row-checkbox-outer");
                var layer = jqCheckOuter.attr("data-tree-layer");
                //获取当前勾选节点的所有前置节点
                var jqPrevAllCheckOuters = jqCheckOuter.prevAll(".hci-grid-body-row-checkbox-outer");
                var pervLayer = layer - 1;
                var prevAllCheckOuterJSON = {};
                jqPrevAllCheckOuters.each(function () {
                    var trIndex = $(this).index();
                    var _layer = $(this).attr("data-tree-layer");
                    if (_layer == pervLayer) {
                        prevAllCheckOuterJSON[_layer] = $(this).find(".hci-grid-body-checkbox");
                        pervLayer = $("#" + self.ids.bodyRowsId).find(".hci-grid-body-row-checkbox-outer").eq(trIndex).attr("data-tree-layer") - 1;
                    }
                    if (_layer == 0) {
                        return false;
                    }
                });
                $.each(prevAllCheckOuterJSON, function (key, item) {
                    jqCheckboxArray.push(item);
                })
            }
            //获取父节点
            if (self.params.showType == "tree" && self.params.row.checkLinkageParent && isCheck) {
                setParentArray();
            }
            if (self.params.showType == "tree" && self.params.row.unCheckLinkageParent && !isCheck) {
                setParentArray();
            }
            //获取节点本身
            jqCheckboxArray.push(jqCheckbox);
            var setChildrenArray = function () {
                var jqCheckOuter = jqCheckbox.closest(".hci-grid-body-row-checkbox-outer");
                var layer = jqCheckOuter.attr("data-tree-layer");
                var jqNextAllCheckOuters = jqCheckOuter.nextAll(".hci-grid-body-row-checkbox-outer");
                jqNextAllCheckOuters.each(function () {
                    var _layer = $(this).attr("data-tree-layer");
                    if (layer >= _layer) {
                        return false;
                    }
                    jqCheckboxArray.push($(this).find(".hci-grid-body-checkbox"));
                });
            }
            //获取子节点
            if (self.params.showType == "tree" && self.params.row.checkLinkageChildren && isCheck) {
                setChildrenArray();
            }
            if (self.params.showType == "tree" && self.params.row.unCheckLinkageChildren && !isCheck) {
                setChildrenArray();
            }
        }
        $.each(jqCheckboxArray, function () {
            var _jqCheckbox = $(this);
            var jqCheckboxOuter = $(this).closest(".hci-grid-body-row-checkbox-outer");
            var primaryKeyValue = jqCheckboxOuter.data("primaryKeyValue");
            var rowData = self.params.resultDataJSON[primaryKeyValue];
            if (typeof (self.params.row.onCheck) == "function") {
                self.params.row.onCheck(isCheck, rowData);
            }
            if (!isCheck) {
                _jqCheckbox.removeClass("hci-grid-checked");
            } else {
                if (self.params.row.checkbox == 1) {
                    $("#" + self.ids.bodyRowsId).find(".hci-grid-checked").removeClass("hci-grid-checked");
                }
                _jqCheckbox.addClass("hci-grid-checked");
            }
        });
    };
    //获取当前页最后一条数据
    HCIGrid.prototype.getCurPageLastRow = function () {
        var self = this;
        var rowIndex = self.getRowCountInPage();
        return self.getRowData(rowIndex);
    };
    //获取指定的行数
    HCIGrid.prototype.getRowData = function (rowIndex) {
        var self = this;
        var rowData = null;
        var index = rowIndex - 1;
        if (index >= 0) {
            var primaryKeyValue = $("#" + self.ids.bodyRowsId).find("table:first").find("tr").eq(index).data("primaryKeyValue");
            rowData = self.params.resultDataJSON[primaryKeyValue];
        }
        return rowData;
    }
    return HCIGrid;

});